package com.vince.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vince.model.domain.User;
import com.vince.model.service.UserService;
import com.vince.util.DBUtil;

/**
 * 用户登录的处理流程
 * 保存用户信息到cookie和session
 * @author susp
 *
 */
@WebServlet("/servlet/loginservlet")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		//用户登录验证
		resp.setCharacterEncoding("utf-8");
		String name=req.getParameter("name");
		String pwd=req.getParameter("pwd");
		String flag=req.getParameter("islogin");
		System.out.println("name"+name+", pwd "+pwd);

		String usertype=req.getParameter("qx");
		//请求参数封装到对象中
		User user=new User();
		user.setUsername(name);
		user.setPassword(pwd);
		//用户验证
		UserService us=new UserService();
		try {
			if(us.checkUser(user)){//验证通过
				if("y".equals(flag)){
					//保存用户名和密码到cookie中
					Cookie namecookie=new Cookie("username", user.getUsername());
					namecookie.setMaxAge(60*60*24*3);
					Cookie pwdcookie=new Cookie("password", user.getPassword());
					pwdcookie.setMaxAge(60*60*24*3);
					namecookie.setPath(req.getContextPath());//设置路径，该路径下都可访问该cookie
					pwdcookie.setPath(req.getContextPath());
					resp.addCookie(namecookie);
					resp.addCookie(pwdcookie);
				}
				//通过session保存用户信息
				req.getSession().setAttribute("user", user);
				
				if("user".equals(usertype)){//普通用户跳转到orderlist
					//登录成功后，进入该用户对应的订单列表页面
					resp.sendRedirect(req.getContextPath()+"/servlet/orderservlet?method=list");//重定向,该request和response生命周期结束
					
				}else if("adminer".equals(usertype)){//管理员跳转到用户管理界面
					req.getRequestDispatcher("/view/user/manage.jsp").forward(req,resp);
				}
				
			}else{//验证失败
				req.setAttribute("message", "用户名或密码错误，请重新输出");
				req.getRequestDispatcher("/view/share/login/login.jsp").forward(req, resp);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

}
